package com.margo.project.netty.zk.zkcodec.create;

import java.util.List;

import com.margo.project.netty.common.SerializeUtils;
import com.margo.project.netty.zk.bean.create.MargoZKAcl;
import com.margo.project.netty.zk.bean.create.MargoZKAclId;
import com.margo.project.netty.zk.bean.create.MargoZKCreateRequest;
import com.margo.project.netty.zk.bean.create.MargoZKCreateResponse;
import com.margo.project.netty.zk.registrys.MargoZKCaches;
import com.margo.project.netty.zk.zkcodec.MargoZKAbstractCodec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

public class MargoZKCreateCodec extends MargoZKAbstractCodec<MargoZKCreateRequest> {
    public MargoZKCreateCodec(MargoZKCaches codecRegistry) {
        super(codecRegistry);
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, MargoZKCreateRequest msg, ByteBuf out) throws Exception {
        out.writeInt(msg.getXid());
        out.writeInt(msg.getType());
        String path = msg.getPath();
        SerializeUtils.writeStringToBuffer(path, out);
        byte [] bytes = msg.getData();
        SerializeUtils.writeByteArrToBuffer(bytes, out);
        List<MargoZKAcl> list = msg.getAcl();
        if (list == null) {
            out.writeInt(-1);
        }else {
            out.writeInt(list.size());
            for(MargoZKAcl acl : list){
                out.writeInt(acl.getPerms());
                MargoZKAclId zkAclId = acl.getId();
                SerializeUtils.writeStringToBuffer(zkAclId.getScheme(), out);
                SerializeUtils.writeStringToBuffer(zkAclId.getId(), out);
            }
        }
        out.writeInt(msg.getFlags());
    }

    /**
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    	MargoZKCreateResponse zkCreateResponse = new MargoZKCreateResponse();
        int xid = in.readInt();
        long zxid = in.readLong();
        int err = in.readInt();
        zkCreateResponse.setXid(xid);
        zkCreateResponse.setZxid(zxid);
        zkCreateResponse.setErr(err);
        if(err == 0){
           String path = SerializeUtils.readStringToBuffer(in);
           out.add(path);
           zkCreateResponse.setPath(path);
        }
        codecRegistry.putResp(xid, zkCreateResponse);
    }
}
